package com.cargohu.aishouyu.auth.controller;

import com.cargohu.aishouyu.auth.constant.LoginConstant;
import com.cargohu.aishouyu.auth.service.MobileLoginService;
import com.cargohu.aishouyu.auth.vo.LoginTokenVo;
import com.cargohu.aishouyu.auth.vo.MemberLoginVo;
import com.cargohu.aishouyu.common.CommonConstants;
import com.cargohu.aishouyu.framework.response.ApiResult;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

/**
 * @author aaron.wang
 * @date 2022/6/26
 **/
@Slf4j
@RestController
@Tag(name = "登录(移动端)")
@RequestMapping(CommonConstants.API_APP_PATH)
public class MobileLoginController {

    @Autowired
    private MobileLoginService mobileLoginService;

    /**
     * 微信登录
     *
     * @return
     * @throws Exception
     */
    @GetMapping("/wx-login/{code}")
    @Operation(summary = "微信登录")
    public ApiResult<LoginTokenVo> login(@Valid @PathVariable String code, HttpServletResponse response) throws Exception {
        LoginTokenVo loginTokenVo = mobileLoginService.login(code);
        // 输出token到cookie
        Cookie cookie = new Cookie(LoginConstant.TOKEN_NAME, loginTokenVo.getToken());
        response.addCookie(cookie);
        return ApiResult.success(loginTokenVo);
    }



    /**
     * 手机短信登录
     *
     * @return
     * @throws Exception
     */
    @GetMapping("/sms-login/{phone}/{code}")
    @Operation(summary = "手机短信登录")
    public ApiResult<LoginTokenVo> sms(@Valid @PathVariable String phone, @Valid @PathVariable String code, HttpServletResponse response) throws Exception {
        LoginTokenVo loginTokenVo = mobileLoginService.login(phone,code);
        // 输出token到cookie
        Cookie cookie = new Cookie(LoginConstant.TOKEN_NAME, loginTokenVo.getToken());
        response.addCookie(cookie);
        return ApiResult.success(loginTokenVo);
    }

    /**
     * 获取登录用户信息
     *
     * @return
     * @throws Exception
     */
    @PostMapping("/user-info")
    @Operation(summary = "获取登录用户信息")
    public ApiResult<MemberLoginVo> getLoginUserInfo() throws Exception {
        return ApiResult.success(mobileLoginService.getLoginUserInfo());
    }

    /**
     * 退出
     *
     * @return
     * @throws Exception
     */
    @PostMapping("/mobile-logout")
    @Operation(summary = "退出")
    public ApiResult<Boolean> logout() throws Exception {
        mobileLoginService.logout();
        return ApiResult.success();
    }

    @GetMapping("/send-sms/{mobile}")
    @Operation(summary = "获取验证码")
    public ApiResult<String> sendSmsCode(@Valid @PathVariable String mobile) {
        return ApiResult.success(mobileLoginService.sendSmsCode(mobile));
    }

}
